package com.blyat.xsoft.gateway.ribbon.router.file;

import com.alibaba.fastjson.JSON;
import com.blyat.xsoft.gateway.ribbon.router.RouteDefinitionLoader;
import org.springframework.cloud.gateway.route.RouteDefinition;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Auther: syh
 * @Date: 2020/8/21
 * @Description:
 */
public class FileRouteDefinitionLoader implements RouteDefinitionLoader {
    private String routersFile;
    private Long lastModified = 0L;

    public FileRouteDefinitionLoader(String routersFile) {
        this.routersFile = routersFile;
    }

    @Override
    public List<RouteDefinition> load() throws Exception {
        String content = Files.lines(Paths.get(
                this.getClass().getClassLoader().getResource(routersFile).toURI()
        )).collect(Collectors.joining());
        return JSON.parseArray(content, RouteDefinition.class);
    }

    @Override
    public boolean reload() {
        File file = new File(this.getClass().getClassLoader().getResource(routersFile).getPath());
        if (file.lastModified() > lastModified) {
            lastModified = file.lastModified();
            return true;
        }
        return false;
    }
}
